<template>
  <div class="page">
    <header class="header">
      <h1>🎬 电影目录与筛选</h1>
      <div class="toolbar">
        <div class="search">
          <el-input
            v-model="q"
            placeholder="搜索标题/别名/演员（支持拼音）..."
            @input="onType"
            @keyup.enter="applyFilters"
            clearable
          >
            <template #append>
              <el-button @click="applyFilters" :icon="Search">搜索</el-button>
            </template>
          </el-input>
          
          <div v-if="suggestions.length" class="suggest">
            <el-tag
              v-for="s in suggestions"
              :key="s"
              class="item"
              @click="chooseSuggest(s)"
              size="small"
              effect="plain"
            >
              {{ s }}
            </el-tag>
          </div>
          
          <div v-if="history.length" class="history">
            <span>历史：</span>
            <el-tag
              v-for="h in history"
              :key="h"
              class="item"
              @click="chooseSuggest(h)"
              size="small"
              type="info"
              closable
              @close="removeHistoryItem(h)"
            >
              {{ h }}
            </el-tag>
            <el-button @click="clearHistory" size="small" type="danger" text>清空</el-button>
          </div>
        </div>

        <div class="filters">
          <div class="group">
            <label>电影分类：</label>
            <el-select v-model="categoryId" placeholder="选择分类" size="small" clearable 
            
           style="width: 120px;"
            >
              <el-option label="全部" :value="null" />
              <el-option 
                v-for="category in categories" 
                :key="category.id" 
                :label="category.name" 
                :value="category.id" 
              />
            </el-select>
          </div>

          <div class="group">
            <label>年份区间：</label>
            <el-input-number v-model.number="yearMin" :min="1900" :max="2100" size="small" />
            <span>—</span>
            <el-input-number v-model.number="yearMax" :min="1900" :max="2100" size="small" />
          </div>

          <div class="group">
            <label>评分区间：</label>
            <el-input-number v-model.number="rateMin" :min="0" :max="10" :step="0.1" size="small" />
            <span>—</span>
            <el-input-number v-model.number="rateMax" :min="0" :max="10" :step="0.1" size="small" />
          </div>

          <div class="group">
            <label>排序：</label>
            <el-select v-model="sortBy" size="small">
              <el-option value="popularity" label="热度" />
              <el-option value="rating" label="评分" />
              <el-option value="year" label="年份" />
              <el-option value="duration" label="时长" />
            </el-select>
            <el-select v-model="sortDir" size="small">
              <el-option value="desc" label="降序" />
              <el-option value="asc" label="升序" />
            </el-select>
            <el-button @click="applyFilters" size="small" type="primary">应用筛选</el-button>
            <el-button @click="resetFilters" size="small">重置</el-button>
          </div>
        </div>
      </div>
    </header>

    <main>
      <div v-if="loading" class="grid">
        <SkeletonCard v-for="n in 8" :key="n" />
      </div>

      <div v-else>
        <div v-if="movies.length === 0" class="empty">未找到符合条件的影片</div>
        <div class="grid">
          <div class="card" v-for="m in movies" :key="m.id" @click="toDetail(m.id)">
            <img :src="m.cover" :alt="m.title">
            <div class="card-body">
              <div class="card-title">{{ m.title }}</div>
              <div class="card-meta">
                <span>年份：{{ m.year }}</span> ·
                <span>评分：{{ m.rating }}</span>
              </div>
            </div>
          </div>
        </div>

        <div class="pager">
          <el-pagination
            v-model:current-page="page"
            :page-size="pageSize"
            :total="total"
            :pager-count="5"
            layout="prev, pager, next, jumper"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </main>
  </div>
</template>

<script setup>
import { onMounted, ref, computed, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useMovieStore } from '../store/index';
import SkeletonCard from '../components/SkeletonCard.vue';
import { Search } from '@element-plus/icons-vue';

const store = useMovieStore();
const router = useRouter();
const route = useRoute();

// 查询与筛选参数
const q = ref(route.query.q?.toString() || '');
const categoryId = ref(route.query.categoryId ? Number(route.query.categoryId) : null);
const yearMin = ref(Number(route.query.ymin) || 1900);
const yearMax = ref(Number(route.query.ymax) || 2100);
const rateMin = ref(Number(route.query.rmin) || 0);
const rateMax = ref(Number(route.query.rmax) || 10);
const sortBy = ref(route.query.sortBy?.toString() || 'year');
const sortDir = ref(route.query.sortDir?.toString() || 'desc');
const pageSize = 12;
const page = ref(Number(route.query.page) || 1);

// 实时数据
const movies = ref([]);
const total = ref(0);
const loading = ref(false);
const categories = ref([]);

// 计算总页数
const totalPages = computed(() => Math.max(1, Math.ceil(total.value / pageSize)));

// 加载电影数据
const loadMovies = async () => {
  loading.value = true;
  try {
    const params = {
      page: page.value - 1,
      size: pageSize,
      search: q.value || undefined,
      categoryId: categoryId.value || undefined,
      yearMin: yearMin.value || undefined,
      yearMax: yearMax.value || undefined,
      ratingMin: rateMin.value || undefined,
      ratingMax: rateMax.value || undefined,
      sortBy: sortBy.value,
      sortDir: sortDir.value,
      status:'published'
    };
    
    const response = await store.searchMovies(params);
    movies.value = response.content || response;
    total.value = response.totalElements || response.length || 0;
  } catch (error) {
    console.error('加载电影数据失败:', error);
  } finally {
    loading.value = false;
  }
};

// 加载分类列表
const loadCategories = async () => {
  try {

    const response = await store.getActiveCategoriesByType('movie');
    categories.value = response.data || response;
  } catch (error) {
    console.error('加载分类列表失败:', error);
  }
};

onMounted(async () => {
  await Promise.all([loadMovies(), loadCategories()]);
});

// 搜索联想与历史
const suggestions = ref([]);
const history = computed(() => store.searchHistory);
const onType = () => {
  // 实时搜索建议可以保留，但需要后端支持
  suggestions.value = [];
};
const chooseSuggest = (s) => { q.value = s; applyFilters(); };
const clearHistory = () => store.clearHistory();
const removeHistoryItem = (item) => store.removeHistoryItem(item);

// 分页处理
const handlePageChange = (newPage) => {
  page.value = newPage;
  applyFilters();
};

// 应用筛选并写入路由参数
const applyFilters = async () => {
  router.replace({
    name: 'home',
    query: {
      q: q.value || undefined,
      categoryId: categoryId.value || undefined,
      ymin: yearMin.value || undefined,
      ymax: yearMax.value || undefined,
      rmin: rateMin.value || undefined,
      rmax: rateMax.value || undefined,
      sortBy: sortBy.value || undefined,
      sortDir: sortDir.value || undefined,
      page: page.value > 1 ? page.value : undefined
    }
  });
  
  if (q.value) {
    store.addHistory(q.value);
  }
  
  await loadMovies();
};

const resetFilters = () => {
  q.value = '';
  categoryId.value = null;
  yearMin.value = 1900;
  yearMax.value = 2100;
  rateMin.value = 0;
  rateMax.value = 10;
  sortBy.value = 'year';
  sortDir.value = 'desc';
  page.value = 1;
  applyFilters();
};

const toDetail = (id) => {
  router.push({ name: 'detail', params: { id } });
};

// 监听路由参数变化
watch(() => route.query, () => {
  q.value = route.query.q?.toString() || '';
  categoryId.value = route.query.categoryId ? Number(route.query.categoryId) : null;
  yearMin.value = Number(route.query.ymin) || 1900;
  yearMax.value = Number(route.query.ymax) || 2100;
  rateMin.value = Number(route.query.rmin) || 0;
  rateMax.value = Number(route.query.rmax) || 10;
  sortBy.value = route.query.sortBy?.toString() || 'year';
  sortDir.value = route.query.sortDir?.toString() || 'desc';
  page.value = Number(route.query.page) || 1;
  
  loadMovies();
}, { immediate: true });
</script>

<style scoped>
.page { 
  max-width: 1200px; 
  margin: 0 auto; 
  padding: 12px; 
  color: #e9eef9; 
  width: 100%;
  box-sizing: border-box;
}
.header h1 { margin: 6px 0 12px; }
.toolbar { display: grid; gap: 12px; }
.search { position: relative; }
.search input { width: 100%; padding: 8px 10px; border-radius: 8px; border: 1px solid #2a3040; background: #181c24; color: #e9eef9;}
.suggest, .history { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 6px; }
.item { padding: 4px 8px; border-radius: 999px; border: 1px solid #2a3040; background: #1b2230; color: #cfe1ff; cursor: pointer; }
.clear { padding: 4px 8px; border-radius: 8px; border: 1px solid #2a3040; background: #1b2230; color: #ff9aa5; cursor: pointer; }

.filters { display: grid; gap: 8px; }
.group { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
.group input, .group select { padding: 8px 10px; border-radius: 8px; border: 1px solid #2a3040; background: #181c24; color: #e9eef9;}
.btn { padding: 8px 12px; border-radius: 8px; border: 1px solid #2a3040; background: #1b2230; color: #cfe1ff; cursor: pointer; }
.chips { display: flex; flex-wrap: wrap; gap: 6px; }
.chip { padding: 6px 10px; border-radius: 999px; border: 1px solid #2a3040; background: #1b2230; color: #cfe1ff; cursor: pointer; }
.chip.active { background: #4f8cff; border-color: #4f8cff; color: #fff; }

.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 12px; margin-top: 16px; }
.card { background: #181c24; border: 1px solid #2a3040; border-radius: 12px; overflow: hidden; cursor: pointer; }
.card img { width: 100%; height: 240px; object-fit: cover; background: #000; }
.card-body { padding: 10px 12px; }
.card-title { font-weight: 600; }
.card-meta { font-size: 12px; color: #9aa6b2; }
.tags .tag { display: inline-block; background: #25304a; color: #cfe1ff; padding: 3px 8px; border-radius: 999px; margin-right: 8px; font-size: 12px; }

.error { color: #ff5c7a; }
.empty { color: #9aa6b2; padding: 20px; text-align: center; }
</style>